package com.zj.leetcode.medium.tree;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: algorithm
 * @description: 填充每个节点的下一个右侧节点指针 II
 * 117 populating-next-right-pointers-in-each-node-ii
 * @author: Zhang Bo
 * @create: 2022-06-28 18:05:03
 **/
public class PopulatingNextRightPointersInEachNodeIi {
    public static void main(String[] args) {
        Solution solution = new PopulatingNextRightPointersInEachNodeIi().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    ;

    class Solution {
        public Node connect(Node root) {
            if (root == null) {
                return root;
            }
            Queue<Node> queue = new LinkedList<>();
            queue.add(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                for (int i = 0; i < size; i++) {
                    Node poll = queue.poll();
                    if (poll != null) {
                        if (i < (size - 1)) {
                            poll.next = queue.peek();
                        }

                        if (poll.left != null) {
                            queue.add(poll.left);
                        }
                        if (poll.right != null) {
                            queue.add(poll.right);
                        }
                    }
                }
            }
            return root;

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
